package com.icss.train_sys_back.controller.admin.train_manage;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.icss.train_sys_back.entity.*;
import com.icss.train_sys_back.entity.ticket_manage.TicketNumberEntity;
import com.icss.train_sys_back.entity.train_manage.StationEntity;
import com.icss.train_sys_back.entity.train_manage.TrainEntity;
import com.icss.train_sys_back.entity.train_manage.TrainNumberEntity;
import com.icss.train_sys_back.entity.train_manage.TrainStationEntity;
import com.icss.train_sys_back.mapper.train_manage.StationMapper;
import com.icss.train_sys_back.service.train_manage.TrainNumberService;
import com.icss.train_sys_back.service.train_manage.TrainService;
import com.icss.train_sys_back.utils.PositionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author wk
 * @desc
 * @date 2025/9/25 16:56
 */
@RestController
@RequestMapping("/admin/train_number")
@Slf4j
public class TrainNumberController {
    @Autowired
    private TrainNumberService trainNumberService;
    @Autowired
    private TrainService trainService;
    @Autowired
    private StationMapper stationMapper;

    @GetMapping("/getTrainNumberList")
    public ResponseResult getTrainNumberList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String trainNumber,
            @RequestParam(required = false) Integer status
    ) {
        log.info("车次列表分页+条件检索： page={},pageSize={},trainNumber={},status={}", page, pageSize, trainNumber, status);

        PageHelper.startPage(page, pageSize);
        List<TrainNumberEntity> trainNumberList = trainNumberService.findTrainNumberList(trainNumber, status);

        PageInfo<TrainNumberEntity> pageInfo = new PageInfo<>(trainNumberList);

        return ResponseResult.success(pageInfo);
    }

    @PostMapping("/update")
    public ResponseResult updateTrainNumber(@RequestBody TrainNumberEntity trainNumber) {
        //判断始发站和终点站是不是同一个站
        if (trainNumber.getStartStation().equals(trainNumber.getEndStation())) {
            return ResponseResult.fail(ResultEnum.START_END_STATION_ERROR);
        }
        boolean res = trainNumberService.updateTrainNumber(trainNumber);
        return res ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    @PostMapping("/add")
    public ResponseResult addTrainNumber(@RequestBody TrainNumberEntity trainNumber) {
        //判断始发站和终点站是不是同一个站
        if (trainNumber.getStartStation().equals(trainNumber.getEndStation())) {
            return ResponseResult.fail(ResultEnum.START_END_STATION_ERROR);
        }
        boolean res = trainNumberService.addTrainNumber(trainNumber);
        return res ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //删除车次
    @DeleteMapping("/delete/{id}")
    public ResponseResult deleteTrainNumber(@PathVariable("id") Integer id) {
        boolean res = trainNumberService.deleteTrainNumber(id);
        return res ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //查找车站列表(下拉框显示)
    @GetMapping("/findStationList")
    public ResponseResult findStationList() {
        log.info("查找车站列表");
        List<StationEntity> stationEntityList = trainNumberService.findStationList();
        return ResponseResult.success(stationEntityList);
    }

    //添加经停站列表
    @PutMapping("/updateStations/{id}")
    @Transactional
    public ResponseResult updateStations(@PathVariable("id") Integer Id,
                                         @RequestBody List<TrainStationEntity> trainStationList) {
        //类型转换
        log.info("添加经停站 车次Id = {}, 经停站列表 = {} ", Id, trainStationList);
        //根据车次Id获取车次实体，删除车次经停站表需要车次中的车辆号train Number
        TrainNumberEntity trainNumber = trainNumberService.findTrainNumberByTrainId(Id);
        //1.先根据trainNumber删除经停站表的所有数据
        trainNumberService.deleteArriveStationByTrainNumber(trainNumber.getTrainNumber());
        //2.添加经停站表
        //2.1 从集合中获取到每个经停站 -- 根据车站名获取到车站的经纬度信息
        for (TrainStationEntity trainStation : trainStationList) {
            //获取经纬度
            double global_X = trainNumberService.findStationXByStationName(trainStation.getStationName());
            double global_Y = trainNumberService.findStationYByStationName(trainStation.getStationName());

            //2.2 根据车次的始发站名称获取该车次的始发站 -- 获取始发站的经纬度用
            StationEntity start_station = trainNumberService.findStartStationByStartStationName(trainNumber.getStartStation());
            //2.3 计算距离始发站的长度
            Integer distanceFromStart = PositionUtil.getDistance(start_station.getGlobalX(), start_station.getGlobalY(), global_X, global_Y);
            trainStation.setDistanceFromStart(distanceFromStart);
            //经停站插入经停站表
            trainNumberService.insertTrainStation(trainStation);
        }
        //2.4 更新trainNumber表中 经停站数 字段 （传回来的经停站集合的长度）
        trainNumberService.updateTrainNumberStayStationNumber(trainStationList.size(), Id);
        //成功
        return ResponseResult.success();
    }

    //根据车次Id获取经停站列表
    @GetMapping("/getTrainStations/{trainNumberId}")
    public ResponseResult getTrainStations(@PathVariable("trainNumberId") Integer trainNumberId) {
        log.info("根据车次Id获取经停站列表  trainNumberId = {}", trainNumberId);
        List<TrainStationEntity> trainStationEntityList = trainNumberService.findTrainStationsByTrainNumberId(trainNumberId);
        return ResponseResult.success(trainStationEntityList);
    }

    //获取所有车辆返回给前端
    @GetMapping("/getAllTrains")
    public ResponseResult getAllTrains() {
        List<TrainEntity> trainList = trainService.findAllTrains();
        return ResponseResult.success(trainList);
    }

    //获取所有车次列表给前端
    @GetMapping("/getAllTrainNumbers")
    public ResponseResult getAllTrainNumbers() {
        List<TrainNumberEntity> trainNumberEntityList = trainService.findAllTrainNumbers();
        return ResponseResult.success(trainNumberEntityList);
    }

    //根据车次Id获取车次信息
    @GetMapping("/getDetail/{trainNumberId}")
    public ResponseResult getDetailById(@PathVariable("trainNumberId") Integer trainNumberId) {
        log.info("根据id查询车次详情信息 trainNumberId = {}", trainNumberId);
        TrainNumberEntity trainNumberById = trainNumberService.findTrainNumberByTrainId(trainNumberId);
        return ResponseResult.success(trainNumberById);
    }

    //根据车次Id获取票数信息
    @GetMapping("/getTicketNumber/{trainNumberId}/{carriageType}")
    public ResponseResult getTicketNumberById(@PathVariable("trainNumberId") Integer trainNumberId,
                                              @PathVariable("carriageType") Integer carriageType) {
        log.info("根据车次Id获取票数信息 trainNumberId = {} , carriageType = {}", trainNumberId, carriageType);
        TicketNumberEntity ticketNumberEntity = trainNumberService.getTicketNumberById(trainNumberId,carriageType);
        return ResponseResult.success(ticketNumberEntity);
    }


    //车次添加脚本
    @GetMapping("/addTrainNumber")
    public void addTrainNumber() {
        Random random = new Random();
        //查询所有的车辆号
        List<TrainEntity> allTrains = trainService.findAllTrains();
        List<TrainNumberEntity> trainNumberEntityList = new ArrayList<>();
        //查询所有的车站  -- 随机选择始发站和终点站
        List<StationEntity> stationList = stationMapper.findStationList(null, null);
        for (int i = 0; i < 10; i++) {
            for (TrainEntity train : allTrains) {
                //随机发车时间和到达时间
                LocalDateTime now = LocalDateTime.now();
                // 发车时间：未来1-30天内随机
                int daysFromNow = random.nextInt(30) + 1;
                int hour = random.nextInt(24); // 0-23点
                int minute = random.nextInt(60);

                LocalDateTime startTime = now.plusDays(daysFromNow)
                        .withHour(hour)
                        .withMinute(minute)
                        .withSecond(0)
                        .withNano(0);

                // 到达时间：发车后1-10小时
                int travelHours = random.nextInt(10) + 1;
                LocalDateTime arriveTime = startTime.plusHours(travelHours);

                //状态为 1 -- 正常
                TrainNumberEntity trainNumber = new TrainNumberEntity(null, train.getTrainNumber(),
                        stationList.get(random.nextInt(stationList.size())).getStationName(),
                        stationList.get(random.nextInt(stationList.size())).getStationName(),
                        0, 1, startTime, arriveTime, now, now, null);
                trainNumberEntityList.add(trainNumber);
            }
        }
        trainNumberService.batchAdd(trainNumberEntityList);

    }


}
